<?php
namespace App\GraphQL\Mutations\Group;

use App\Models\Group;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use App\Models\MerchantStatistical;
use App\Models\DistributorStatistical;
use Illuminate\Support\Facades\DB;
use App\Models\Device;

class Delete
{

    /**
     * Return a value for the field.
     *
     * @param null $rootValue
     *            Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param mixed[] $args
     *            The arguments that were passed into the field.
     * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context
     *            Arbitrary data that is shared between all fields of a single query.
     * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo
     *            Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        DB::transaction(function () use ($args) {
            $group = $this->validate($args['id']);
            // 找出被删掉的成员
            $deleteMembers = $group->members;
            $deleteMembers->map(function ($member) use (&$group) {
                if ($member->role === 'MERCHANT') {
                    // 更新终端伙伴
                    $merchantStatistical = MerchantStatistical::firstOrCreate([
                        'user_id' => $member->user_id
                    ]);
                    $merchantStatistical->decrement('link_group_count');
                    $merchantStatistical->decrement('link_device_count', $group->devices->count());
                } else if ($member->role === 'DISTRIBUTOR') {
                    // 更新分销商
                    $distributorStatistical = DistributorStatistical::firstOrCreate([
                        'user_id' => $member->user_id
                    ]);
                    $distributorStatistical->decrement('link_group_count');
                    $distributorStatistical->decrement('link_device_count', $group->devices->count());
                }
            });

            $group->members()->delete();
            Device::where('device_group_id', $group->id)->update([
                'device_group_id' => null
            ]);
            $group->delete();
        });
        return [
            'status' => '200',
            'message' => '删除成功'
        ];
    }

    public function validate($id)
    {
        // 验证用户是否存在
        $old = Group::find($id);
        if (! $old) {
            throw new \Exception('群组不存在!');
        }
        return $old;
    }
}
